/*
 * Copyright 2011 The Rusted Roof, LLC.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package org.proteusframework.platformservice.persistence.c14n;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author Tacoma Four
 */
final class BooleanArrayC14NHandler extends AbstractC14NHandler
{

    @Override
    public Object fromC14N(byte[] bytes)
    {
        int idx = 0;

        boolean[] booleanValues = new boolean[bytes.length];
        for (byte rawByte : bytes)
        {
            booleanValues[idx] = (rawByte == 1);
            idx++;
        }

        return booleanValues;
    }

    public byte[] toC14N(Object object)
    {
        byte[] booleanBytes = new byte[0];

        boolean[] booleanValues = (boolean[]) object;

        ByteArrayOutputStream booleanBaos = new ByteArrayOutputStream();

        String booleanHeader = PACKED_BLOB_PREFIX + transposeClassName(boolean[].class.getName()) + PACKED_BLOB_SUFFIX;
        byte[] booleanHeaderBytes = booleanHeader.getBytes();
        booleanBaos.write(booleanHeaderBytes, 0, booleanHeaderBytes.length);

        for (boolean curValue : booleanValues)
        {
            booleanBaos.write(curValue ? (byte) 1 : (byte) 0);
        }

        try
        {
            booleanBaos.flush();
            booleanBaos.close();
            booleanBytes = booleanBaos.toByteArray();
        } catch (IOException e)
        {
            e.printStackTrace();
        }

        return booleanBytes;
    }
}
